package com.lwl.study.config;

import com.lwl.study.zk.MyZkSerializer;
import com.alibaba.druid.pool.DruidDataSource;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

@Component
public class DataSourceUtils {



    public static Connection getConnection() throws SQLException {
        return druidDataSource.getConnection();
    }

    private static DruidDataSource druidDataSource;
    private static ApplicationContext applicationContext;
    private static ZkClient zkClient = new ZkClient("localhost:2181",30000,2147483647,new MyZkSerializer());
    private static String path = "/lagouConfig/dataSource";

    private static Properties loadPropertiesFromString(String source){
        Properties properties = new Properties();
        if(source!=null){
            String[] split = source.split("\n");
            for (String s : split) {
                if(!StringUtils.isEmpty(s)){
                    String[] sub = s.split(": ");
                    if(sub!=null && sub.length>=2 && !StringUtils.isEmpty(sub[0]) && !StringUtils.isEmpty(sub[1])){
                        properties.put(sub[0].trim(),sub[1].trim());
                    }
                }
            }
        }
        System.out.println(properties);
        return properties;
    }

    private static DruidDataSource createDruidDataSourceByProperties(Properties properties){
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl((String) properties.get("datasource.url"));
        datasource.setUsername((String) properties.get("datasource.username"));
        datasource.setPassword((String) properties.get("datasource.password"));
        datasource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        datasource.setValidationQuery("SELECT 1");
        return datasource;
    }


    @PostConstruct
    public void loadConfigProperties() {
        String dataSourceConfig = zkClient.readData(path);
        zkClient.subscribeDataChanges(path, new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                Properties properties = loadPropertiesFromString(o.toString());
                druidDataSource.close();
                druidDataSource = createDruidDataSourceByProperties(properties);
            }
            @Override
            public void handleDataDeleted(String s) throws Exception {

            }
        });
        Properties properties = loadPropertiesFromString(dataSourceConfig);
        druidDataSource = createDruidDataSourceByProperties(properties);
    }


}
